package com.linln.modules.integralmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linln.common.enums.*;
import com.linln.common.utils.CodeUtil;
import com.linln.common.utils.DateUtil;
import com.linln.common.vo.JsonResult;
import com.linln.modules.activityticket.service.ActivityTicketService;
import com.linln.modules.integralmall.domain.IntegralMallService;
import com.linln.modules.integralmall.domain.RotationChart;
import com.linln.modules.integralmall.service.IntegralMallServiceService;
import com.linln.modules.integralmall.repository.IntegralMallServiceMapper;
import com.linln.modules.integralmall.service.RotationChartService;
import com.linln.modules.order.domain.Order;
import com.linln.modules.order.service.OrderService;
import com.linln.modules.points.domain.Points;
import com.linln.modules.points.service.PointsService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import com.linln.modules.ticket.domain.Ticket;
import com.linln.modules.ticket.service.TicketService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.integralmall.service.impl
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.integralmall.service.impl
 * @Description: TODO
 * @date Date : 2020年12月14日 15:41
 */
@Service
public class IntegralMallServiceServiceImpl extends ServiceImpl<IntegralMallServiceMapper, IntegralMallService> implements IntegralMallServiceService {

    @Autowired
    private IntegralMallServiceMapper integralMallMapper;
    @Autowired
    private RotationChartService rotationChartService;
    @Autowired
    private UserService userService;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private ActivityTicketService activityTicketService;
    @Override
    public Map<String, Object> getIntegralMallService(Integer pageNum, Integer limit, String serviceName) {
        PageHelper.startPage(pageNum, limit);
        PageInfo<IntegralMallService> pageInfo = new PageInfo<>(integralMallMapper.getIntegralMallService(serviceName));
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", pageInfo.getList());
        map.put("count", pageInfo.getTotal());
        return map;
    }


    @Override
    @Transactional
    public boolean addIntegralMallService(List<MultipartFile> files, IntegralMallService service) {
        this.save(service);
        return rotationChartService.addRotationChart(service.getImsId(), files);
    }

    @Override
    @Transactional
    public boolean updateIntegralMallService(List<MultipartFile> files, List<Integer> status, IntegralMallService service) {
        this.updateById(service);
        return rotationChartService.updateRotationChart(service.getImsId(), files, status);
    }


    @Override
    @Transactional
    public boolean delIntegralMallService(String serviceId) {
        return this.removeById(serviceId);
    }

    @Value("${server.ip}")
    String ip;
//    @Value("${server.addr}")
//    String addr;
//    @Value("${server.treaty}")
//    String treaty;

    @Override
    public Map<String, Object> getIntegralMallList(Integer pageNum, Integer limit, String serviceTypeId, Integer integral, String integralMallServiceName) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum + 1, limit);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(integralMallMapper.getIntegralMallList(serviceTypeId, integral, integralMallServiceName));
        map.put("total", pageInfo.getTotal());
        List<Map<String, Object>> list = pageInfo.getList();
        //第一张轮播图
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("serviceImg", ip + list.get(i).get("serviceImg"));
        }
        map.put("data", list);
        return map;
    }


    @Override
    public Map<String, Object> getIntegralMallServiceInfo(String serviceId) {
        Map<String, Object> map = new HashMap<>();
        IntegralMallService integralMallServiceInfo = integralMallMapper.getIntegralMallServiceInfo(serviceId);
        List<RotationChart> rotationChatsInfo = rotationChartService.getRotationChatsByServiceId(serviceId);
        Map<String, Object> info = new HashMap<>();
        //轮播图
        rotationChatsInfo.forEach(item -> {
            item.setRcAddress(ip + item.getRcAddress());
        });
        String imsContent = integralMallServiceInfo.getImsContent();
        integralMallServiceInfo.setImsContent(replaceDomainName(imsContent));
        info.put("integralMallServiceInfo", integralMallServiceInfo);
        info.put("rotationChatsInfo", rotationChatsInfo);
        map.put("data", info);
        return map;
    }


    //替换路径
    public String replaceDomainName(String content) {
        Pattern pattern = Pattern.compile("src=(\"|'| |)([\\S]{1,}?|[/]{1,})([/]{1,})(.+?)([/]{1,})(.+?)\\.(png|jpg|jpeg)(\"|'| |/>)");

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {
//            System.out.println("-------------------");
//            String host = matcher.group(4);
//            content = content.replaceAll(matcher.group(2), treaty);
//            return content.replaceAll(host, addr);
//            String imgUrl = matcher.group(2) + matcher.group(3) + matcher.group(4) + matcher.group(5) + matcher.group(6) + "." + matcher.group(7);
//
            String imgIp = matcher.group(2) + matcher.group(3) + matcher.group(4) + matcher.group(5);
            return content.replaceAll(imgIp, ip);
//            System.out.println(host);
//
//            System.out.println(imgUrl);
        }
        return content;
    }

    public JsonResult closeIntegralService(String serviceId, long userId) {
        IntegralMallService integralMallServiceInfo = integralMallMapper.getIntegralMallServiceInfo(serviceId);
        User user = userService.getById(userId);
        Order order = createNotPayOrder(user, integralMallServiceInfo, null, null);
        if (orderService.save(order)) {
            //生成待支付订单
            return JsonResult.ok("生成待支付订单成功").put("orderId", order.getOrderId());
        }
        return JsonResult.error("生成待支付订单失败");
    }


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public JsonResult buyIntegralService(String serviceId, long userId) throws Exception {
        IntegralMallService integralMallServiceInfo = integralMallMapper.getIntegralMallServiceInfo(serviceId);
        User user = userService.getById(userId);
        if (Optional.ofNullable(user.getPointsLeft()).orElse(0) < integralMallServiceInfo.getIntegral()) {
            Order order = createNotPayOrder(user, integralMallServiceInfo, null, null);
            if (orderService.save(order)) {
                //生成待支付订单
                return JsonResult.error("积分不足").put("orderId", order.getOrderId());
            }
            return JsonResult.error("兑换失败");
        }
        //减库存 减积分 加积分记录
        JsonResult jsonResult = reduceStock(integralMallServiceInfo, user);
        if (jsonResult != null) {
            return jsonResult;
        }
        //保存订单信息
        String orderId = createPayOrder(user, integralMallServiceInfo, null);

        if (!Strings.isBlank(orderId)) {
            return JsonResult.ok("兑换成功").put("orderId", orderId);
        }

        throw new Exception("兑换失败");
    }


    //待支付订单支付
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public JsonResult payIntegralService(String orderId, long userId) throws Exception {
        Order order = orderService.getIntegralMallOrderById(orderId);
        IntegralMallService integralMallServiceInfo = integralMallMapper.getIntegralMallServiceInfo(order.getIntegralMallServiceId());
        User user = userService.getById(userId);
        if (Optional.ofNullable(user.getPointsLeft()).orElse(0) < integralMallServiceInfo.getIntegral()) {
            //生成待支付订单
            return JsonResult.error("积分不足").put("orderId", orderId);
        }
        //减库存 减积分 加积分记录
        JsonResult jsonResult = reduceStock(integralMallServiceInfo, user);
        if (jsonResult != null) {
            return jsonResult;
        }
        //保存订单信息
        createPayOrder(user, integralMallServiceInfo, order);
        if (!Strings.isBlank(orderId)) {
            return JsonResult.ok("兑换成功").put("orderId", orderId);
        }

        throw new Exception("兑换失败");

    }


    @Transactional
    //判断是否有库存  减库存 修改积分 添加积分记录
    public JsonResult reduceStock(IntegralMallService integralMallServiceInfo, User user) {
        if (integralMallServiceInfo.getReceivedCount() >= integralMallServiceInfo.getCount()) {
            return JsonResult.error("库存不足");
        }
        //减库存
        if (activityTicketService.buyIntegralService(integralMallServiceInfo.getAtId()) <= 0) {
            return JsonResult.error("库存不足");
        }
        //减积分
        user.setPointsLeft(user.getPointsLeft() - integralMallServiceInfo.getIntegral());
        //修改用户积分
        userService.save(user);

        //添加积分记录
        pointsService.addPoints(new Points(integralMallServiceInfo.getIntegral(),
                PointsEnum.expenditure.getCode(), "兑换" + integralMallServiceInfo.getServiceName(), DateUtil.formatDate(new Date()), String.valueOf(user.getId())));
        return null;
    }

    @Transactional
    //创建支付订单 支付待支付订单
    public String createPayOrder(User user, IntegralMallService ims, Order order) throws RuntimeException {
        Date date;
        String currentDate;
        //订单=null 时间为当前时间
        if (order == null) {
            date = new Date();
            currentDate = DateUtil.formatDate(date);
            //创建待支付订单
            order = createNotPayOrder(user, ims, date, currentDate);
        } else {
            //时间为待支付订单时间
            date = DateUtil.parseDate(order.getOrderTime());
            currentDate = order.getOrderTime();
        }
        //支付时间
        order.setPayTime(currentDate);
        //订单状态
        order.setOrderStatus(OrderEnum.COMPLETED.getCode());
        //移动充值需要添加卡券号码和卡券密码
        if (ims.getServiceTypeId().equals(ServiceTypeEnum.RECHARGE)) {
            Map<String, String> map = new HashMap<>();
            //卡券账号
            map.put("cardNumber", CodeUtil.trans(CodeUtil.createOne()));
            //卡券密码
            map.put("cardPassWord", CodeUtil.trans(CodeUtil.createOne()));
            //json字段   卡券  密码
            order.setOrderProperties(JSON.toJSONString(map));
        }

        //当类型为洗车，维修，安全检测，年审办理 时 生成优惠券
        if (ims.getServiceTypeId().equals(ServiceTypeEnum.WASH) || ims.getServiceTypeId().equals(ServiceTypeEnum.REPAIR) || ims.getServiceTypeId().equals(ServiceTypeEnum.TESTING) || ims.getServiceTypeId().equals(ServiceTypeEnum.YEARRWVIEW)) {
            Ticket ticket = new Ticket();
            //券码
            ticket.setTicketCode(CodeUtil.trans(CodeUtil.createOne()));
            //购买日期
            ticket.setBuyDate(currentDate);
            //状态 未使用
            ticket.setStatus(TicketEnum.NOTUSE.getCode());
            //过期时间 当前时间+活动券指定的时间
            if (ims.getValidDay() != null) {
                ticket.setExpirDate(DateUtil.formatDate(DateUtil.getAppointDate(date, ims.getValidDay()), "yyyy-MM-dd"));
            } else {
                //开始时间
                ticket.setStartDate(ims.getValidStartDate());
                //结束时间
                ticket.setExpirDate(ims.getValidEndDate());
            }
            //券 说明   活动券的说明
            ticket.setExplain(ims.getImsNotice());
            //券类型  活动券类型
            ticket.setServiceTypeId(ims.getServiceTypeId());
            //使用规则id
            ticket.setUseRuleId(ims.getUseRuleId());
            //积分
            ticket.setTicketIntegral(order.getIntegralUseCount());
            //金额
            ticket.setTicketMoney(order.getOrderMoney());
            //用户id
            ticket.setUserId(user.getId());
            //保存服务券
            if (!ticketService.addTicket(ticket)) {
                throw new RuntimeException("保存服务券失败");
            }
        }
        //保存订单
        if (order.getOrderId() == null ? !orderService.save(order) : !orderService.updateById(order)) {
            throw new RuntimeException("保存订单失败");
        }
        return order.getOrderId();
    }

    /**
     * 创建未支付订单
     * @param user 购买用户
     * @param ims 商城服务
     * @param date 时间
     * @param currentDate 字符串时间
     * @return
     */
    private Order createNotPayOrder(User user, IntegralMallService ims, Date date, String currentDate) {
        date = date == null ? new Date() : date;
        currentDate = currentDate == null ? DateUtil.formatDate(date) : currentDate;
        Order order = new Order();
        //订单积分商城服务id
        order.setIntegralMallServiceId(ims.getImsId());
        //订单编号
        order.setOrderNumber(CodeUtil.trans(CodeUtil.createOne()));
        //下单时间
        order.setOrderTime(currentDate);
        //积分
        order.setIntegralUseCount(ims.getIntegral());
        //金额
        order.setOrderMoney(ims.getMoney());
        //支付金额
        order.setActualPayMoney(0D);
        //订单状态 待支付
        order.setOrderStatus(OrderEnum.WAITPAY.getCode());
        //用户
        order.setUserId(user.getId());
        //支付方式  积分
        order.setPayMode(PayModeEnum.INTEGRAL);
        //使用备注
        order.setUseExplain(ims.getImsNotice());
        return order;
    }
//    public static void main(String[] args) {
//        String content = "<p><img src=\"http://192.168.199.190:8089//img/nO6RuYXO.jpg\" style=\"max-width:100%;\" width=\"30%\"><br></p><p><b>12343534564565756767</b><br></p><p>43254325346534342423<b><br></b></p><hr><p>321435345345</p><p><img src=\"http://192.168.199.190:8089//img/cu6hTNCs.jpg\" style=\"max-width:100%;\" width=\"30%\"><br></p>";
//        Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(?:com\\.cn|net\\.cn|org\\.cn|com|net|org|cn|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
//        System.out.println(new IntegralMallServiceServiceImpl().replaceDomainName(content));
//    }


    @Override
    public boolean activityServiceIsItAssociatedByIntegralMall(String activityServiceId) {
        List<IntegralMallService> at_id = this.list(new QueryWrapper<IntegralMallService>().eq("at_id", activityServiceId));
        //判断活动券是否被积分商城服务关联
        return at_id != null && at_id.size() > 0;
    }

    @Override
    public IntegralMallService getIntegralMallServiceById(String imsId) {
        return integralMallMapper.getIntegralMallServiceInfo(imsId);
    }
}
